package com.shujia.spark.stream

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo5RDDtoDS {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .master("local[2]")
      .appName("rdd")
      .getOrCreate()

    import spark.implicits._
    import org.apache.spark.sql.functions._

    val sc: SparkContext = spark.sparkContext


    val ssc = new StreamingContext(sc, Durations.seconds(5))

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)

    val countDS: DStream[(String, Int)] = linesDS.transform(rdd => {
      val countRDD: RDD[(String, Int)] = rdd.
        flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)

      //返回一个新的rdd
      countRDD
    })

    countDS.print()

    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
